/**
 * 上传文件需要
 * @param url
 */
// import { ElMessage } from 'element-plus';
// getObsConfig
// getObsFormUploadConfig
// uploadFile
import request from 'axios';
// 获取密钥配置
let baseUrl = process.env.NODE_ENV === 'development' ? '/apis' : process.env.VUE_APP_WEB_URL;
export const getObsConfig = data =>
  request({
    url: baseUrl + '/obs/getObsConfig',
    method: 'get',
    data,
    headers: {
      Authorization: localStorage.getItem('CLOUD-AFTER-CLASS-TOKEN')
    }
  });
// form 上传时的参数
export const getObsFormUploadConfig = data =>
  request({
    url: baseUrl + '/obs/getObsFormUploadConfig',
    method: 'get',
    data,
    headers: {
      Authorization: localStorage.getItem('CLOUD-AFTER-CLASS-TOKEN')
    }
  });

// 华为云图片上传接口
export const uploadFile = (url, data) =>
  request({
    url,
    method: 'post',
    data: data
  });
// 上传end
/**
 * 上传文件需要
 * @param url
 */
const renderSize = value => {
  if (value == null || value === '') {
    return '0 B';
  }
  let unitArr = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  let index = 0;
  let srcsize = parseFloat(value);
  index = Math.floor(Math.log(srcsize) / Math.log(1024));
  let size = srcsize / Math.pow(1024, index);
  let getSize = String(size.toFixed(2));
  return getSize + unitArr[index];
};
const fileStrInfo = file => {
  return {
    type: file.replace(/.+\./, ''),
    filename: file.replace(/(.*\/)*([^.]+).*/gi, '$2')
  };
};
export const filesParams = file => {
  let name = new Date().getTime() + file.name;

  return {
    name: name, // 文件全名
    fileName: fileStrInfo(name).filename, // 文件名
    fileSuffix: fileStrInfo(name).type, // 文件后缀名
    size: file.size,
    formatSize: renderSize(file.size), // 格式化后的文件大小
    raw: file // 原始文件
  };
};

export function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

async function getOssInfo(dir) {
  return await getObsFormUploadConfig();
}
export function uploadOssFile(file) {
  return new Promise(function (resolve, reject) {
    const { name, size } = filesParams(file);
    getObsConfig().then(res => {
      let { data } = res.data;
      let upUrl = `https://${data.bucketName}.${data.endPoint}`;
      const dir = data.fileUrl + name;
      const baseUrl = `${upUrl}/` + dir;
      // console.log(res, baseUrl, dir);
      getOssInfo(dir)
        .then(resData => {
          const { ak, signature, policy } = resData.data.data;
          const formData = new FormData();
          // 顺序不要乱key,x-obs-acl,content-type,policy,AccessKeyId,signature,file,
          //  保持文件在最低部
          formData.append('key', dir);
          formData.append('x-obs-acl', 'public-read');
          formData.append('content-type', 'text/plain');
          formData.append('policy', policy);
          formData.append('AccessKeyId', ak);
          formData.append('signature', signature);
          formData.append('file', file);
          uploadFile(upUrl, formData)
            .then(() => {
              resolve({ url: baseUrl, size, name: file.name }); // 返回
            })
            .catch(err => {
              reject(err);
            });
        })
        .catch(err => {
          console.log(err);
          // ElMessage.warning('图片秘钥创建失败，请重试');
        });
    });
  });
}
